package com.totoro.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.pojo.*;
import com.totoro.service.*;
import com.totoro.utils.Base64EncryptionUtil;
import lombok.SneakyThrows;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/7/9 16:25
 */
@Controller
@RequestMapping("/productBuy_logic")
public class ProductController {

    @Autowired
    ProductService productService;
    @Autowired
    ShopCouponService shopCouponService;
    @Autowired
    AddressService addressService;
    @Autowired
    EvaluationService evaluationService;
    @Autowired
    ShopService shopService;

    /**
     * 获得商品最大，最小的skuId
     * @param pid
     * @return
     */
    @RequestMapping("/getMiMxSkuId")
    @ResponseBody
    public String getProductMaxAndMinSkuId(@RequestParam("pid") int pid){
        int min = productService.findMinSkuIdByPid(pid);
        int max = productService.findMaxSkuIdByPid(pid);
        return min+","+max;
    }

    /**
     * 初始化Sku -- 获取所有Sku属性
     * @param pid
     * @return
     */
    @SneakyThrows
    @RequestMapping("/initSku")
    @ResponseBody
    public String initSku(@RequestParam("pid") int pid){
        Map<Integer, ProductSpecs> productSpecsMap = productService.findProductSkuNameById(pid);

        // 遍历获取Sku
        List<ProductSpecs> skus = new ArrayList<>();
        String skuCodes = "";
        for (Map.Entry<Integer, ProductSpecs> m : productSpecsMap.entrySet()) {
            skus.add(m.getValue());
            skuCodes+= m.getKey()+",";
        }

        // json数组
        skuCodes = skuCodes.substring(0, skuCodes.length()-1);

        return new ObjectMapper().writeValueAsString(skus)+"<>"+skuCodes;
    }

    /**
     * 获取单个sku重要属性
     * @param skuId
     * @param skuId
     * @return
     */
    @RequestMapping("/getSkuAttr")
    @ResponseBody
    public String getSkuAttr(@RequestParam("skuId") int skuId){
        ProductSpecs productSpecs = productService.findAssignSkuByPidAndSkuId(skuId);
        return productSpecs.getProductSpaceData();
    }

    /**
     * 获取多个sku重要属性
     * @param pid
     * @param skuId
     * @param nowIndex
     * @return
     */
    @SneakyThrows
    @RequestMapping("/getSkuAttrs")
    @ResponseBody
    public String getSkuAttrs(@RequestParam("pid") int pid, @RequestParam("skuId") int skuId, @RequestParam("nowIndex") int nowIndex){
        // 先获取该Sku对应的属性组内容，再根据内容的指定段获取所有由该sku指定段开启的属性组
        ProductSpecs productSpecs = productService.findAssignSkuByPidAndSkuId(skuId);
        String[] skuContent = productSpecs.getProductSpaceData().split(",");
        // 根据nowIndex，循环给值
        String nowParagraph = "";
        for (int i = 0; i <= nowIndex; i++) {
            nowParagraph+=skuContent[i];
            if(i!=nowIndex){
                nowParagraph+=",";
            }
        }

        Map<Integer, ProductSpecs> map = productService.findAssignSkusByPidAndSkuData(pid, nowParagraph);


        // 遍历获取Sku
        List<ProductSpecs> skus = new ArrayList<>();
        String skuCodes = "";
        for (Map.Entry<Integer, ProductSpecs> m : map.entrySet()) {
            skus.add(m.getValue());
            skuCodes+= m.getKey()+",";
        }

        // json数组
        skuCodes = skuCodes.substring(0, skuCodes.length()-1);

        return new ObjectMapper().writeValueAsString(skus)+"<>"+skuCodes;
    }


    /**
     * 获取sku的数据 比如 数量 价格 等等
     * @param skuId
     * @return
     */
    @RequestMapping("/getSkuData")
    @ResponseBody
    public String getSkuData(@RequestParam("skuId") int skuId){
        ProductSpecs productSpecs = productService.findAssignSkuByPidAndSkuId(skuId);
        JSONObject json = JSONObject.fromObject(productSpecs);
        System.out.println(json.toString());
        return json.toString();
    }


    /**
     * 收藏一个商品
     * @param pid
     * @param session
     * @return
     */
    @RequestMapping(value = "/collectProduct", method = RequestMethod.POST)
    @ResponseBody
    public String collectProduct(@RequestParam("pid") int pid, HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        if(null == user){
            String beforeUrl = "/buy.htm?pid="+pid;
            return "/login.htm?ttr="+new String(Base64EncryptionUtil.base64Encrypt(beforeUrl));
        }
        productService.collectProduct(user.getUserId(), pid);
        // 将该商品的收藏数量+1
        productService.updateProductCollectCount(0, pid);
        return "success";
    }

    /**
     * 取消收藏一个商品
     * @param pid
     * @param session
     * @return
     */
    @RequestMapping(value = "/cancelCollectProduct", method = RequestMethod.POST)
    @ResponseBody
    public String cancelCollectProduct(@RequestParam("pid") int pid, HttpSession session){
        User user = (User) session.getAttribute("user");
        productService.cancelCollectProduct(user.getUserId(), pid);
        // 将该商品的收藏数量-1
        productService.updateProductCollectCount(1, pid);
        return "success";
    }

    /**
     * 批量取消收藏
     * @param clids
     * @return
     */
    @RequestMapping(value = "/batchCancelCollectProduct", method = RequestMethod.POST)
    @ResponseBody
    public String batchCancelCollectProduct(@RequestParam("clids[]") Integer[] clids){
        productService.batchReduceProductCollectCount(clids);
        productService.batchDeleteCollectProduct(clids);
        return "success";
    }


    /**
     * 获得所有能使用的优惠券，仅限于单笔订单
     * @param sid
     * @param allPrice
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/getCoupon", method = RequestMethod.POST)
    @ResponseBody
    public String getShopAllCoupon(@RequestParam("sid") int sid, @RequestParam("allPrice") double allPrice, HttpSession session){
        User user = (User) session.getAttribute("user");
        int uid = user.getUserId();
        // 寻找自己在这个店铺能够使用的所有优惠券
        List<ShopCoupon> myCouponList = shopCouponService.findAllCouponByUidAndSid(uid, sid);
        List<String> jsonList = new ArrayList<>();
        if(myCouponList.size() > 0){
            for (int i = 0; i < myCouponList.size(); i++) {
                int scid = myCouponList.get(i).getId();
                String couponTitle = myCouponList.get(i).getCouponTitle();
                String couponInfo = myCouponList.get(i).getCouponInfo();
                // 是否是自己的优惠券
                int isMy = myCouponList.get(i).getMyCoupon().getId();
                // 是否达到了满减额度
                boolean disabled = allPrice>=myCouponList.get(i).getCouponUseMoney()?false:true;
                double money = myCouponList.get(i).getCouponMoney();
                // 组合json
                jsonList.add("{'value':"+scid+",'label':'"+couponTitle+"','info':'"+couponInfo+"','isMy':"+isMy+",'disabled':"+disabled+", 'money':"+money+"}");
            }
        }
        // 序例化
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(jsonList);
    }

    /**
     * 订单页面-获得更多的地址 -- 第四个之后的地址
     * @param session
     * @return
     */
    @SneakyThrows
    @PostMapping("/showMoreAddr")
    @ResponseBody
    public String getUserMoreAddress(HttpSession session){
        User user = (User) session.getAttribute("user");
        int uid = user.getUserId();
        List<Address> addressList = addressService.findAddressByUid(uid);
        for (int i = 0; i < 4; i++) {
            addressList.remove(0);
        }
        // 序列化
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(addressList);
    }

    /**
     * 查找不同类型的商品评论
     * @param type
     * @return
     */
    @SneakyThrows
    @PostMapping("/findTypeComment")
    @ResponseBody
    public String findTypeComment(@RequestParam("pid") Integer pid, @RequestParam("type") Integer type, @RequestParam("sort") String sort){
        List<ProductComment> productComments = evaluationService.findProductAllEvaluationByPid(pid, type, sort);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(productComments);
    }

    @RequestMapping(value = "/collectShop", method = RequestMethod.POST)
    @ResponseBody
    public String collectShop(@RequestParam("sid") int sid, HttpSession session){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "error";
        }
        CollectShop collectShop = shopService.checkUserCollectShop(user.getUserId(), sid);
        if(null != collectShop){
            return "error";
        }

        shopService.collectShop(user.getUserId(), sid);
        return "success";
    }

}
